package com.example.livesettingtest;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;



import java.util.HashMap;
import java.util.Map;

public class WebViewBrowser extends AppCompatActivity {
    String mUrl;
    String mTitle;
    private ProgressBar mProgressBar;
    private WebsiteChangeListener mWebsiteChangeListener;
    WebView webview;
    String TAG = "WebViewBrowser";
    //18829553960     123456
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_about);
        super.onCreate(savedInstanceState);
        getLastIntent(); //获得上一页传递过来的URL
        initView();

    }
    @Override
    protected void onDestroy() {
        if(webview != null)
        {
            webview.destroy();;
            webview = null;
        }
        super.onDestroy();
    }




    private void initView() {
       /* TextView tvTitle = this.findViewById(R.id.tv_title);
        tvTitle.setText(mTitle);*/
        initWebView();
        initProgressBar();
        webview.addView(mProgressBar);

    }


    public void initWebView()
    {

        webview = (WebView)findViewById(R.id.webviewAbout);
        WebSettings webSettings =  webview.getSettings();
/*        webSettings.setJavaScriptEnabled(true);*/
        webSettings =  webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowUniversalAccessFromFileURLs(false);
        webSettings.setAllowFileAccessFromFileURLs(false);
        webSettings.setBlockNetworkImage(false);
        webSettings.setBlockNetworkLoads(false);
        //gxw- webSettings.setFantasyFontFamily();
        webSettings.setDatabaseEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setDisplayZoomControls(true);
        webSettings.setDomStorageEnabled(true);
        //webSettings.setFantasyFontFamily();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLightTouchEnabled(false);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webview.requestFocus();
        webview.setWebViewClient(new MyWebViewClient());
        webview.setWebChromeClient(webChromeClient);



      /*  Map extraHeaders = new HashMap();
        extraHeaders.put("Referer", "www.qianniukeji.vip");//例如 http://www.baidu.com www.qianniukeji.vip*/
      //gxw-  mUrl = "http://www.qianniukeji.vip";
        webview.loadUrl(mUrl);
        //webview.loadUrl(mUrl);
        
    }
    private void initProgressBar() {


        //================顶部进度条的初始化===================
        mProgressBar = new ProgressBar(WebViewBrowser.this, null,
                android.R.attr.progressBarStyleHorizontal);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, 8);
        mProgressBar.setLayoutParams(layoutParams);

        Drawable drawable = this.getResources().getDrawable(
                R.drawable.web_progress_bar_states);
        mProgressBar.setProgressDrawable(drawable);
    }
    public void getLastIntent() {

        Intent i = this.getIntent();

        if(i != null)
        {
            Bundle b = i.getExtras();

            if(b != null)
            {
                mUrl = b.getString("url");
                mTitle = b.getString("title");
                Log.i(TAG,mUrl);
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //return super.onKeyDown(keyCode, event);

        goBackWebPage(keyCode);
        /*if((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
            webview.goBack();
            Log.i(TAG,"goBack");
            return true;
        }
        else if((keyCode == KeyEvent.KEYCODE_BACK) && !(webview.canGoBack()))
        {
            WebViewBrowser.this.finish();
        }*/


     /*  gxw-s if((keyCode == KeyEvent.KEYCODE_BACK))
        {
            WebViewBrowser.this.finish();
        }gxw-e*/
        return false;
    }

    public boolean goBackWebPage(int keyCode)
    {

        if((keyCode == KeyEvent.KEYCODE_BACK || keyCode == -4 ) && webview.canGoBack()){
            webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//点后退加载缓存
            webview.goBack();
            Log.i(TAG,"goBack");
            return true;
        }
        else if((keyCode == KeyEvent.KEYCODE_BACK || keyCode == -4) && !(webview.canGoBack()))
        {
            WebViewBrowser.this.finish();
        }

        return false;

    }



    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i(TAG, url);
            //方案1 目前比较靠谱 WEBVIEW自己添加header Referer :如下方案可在非微信内部WebView的H5页面中调出微信支付START
            if (url.startsWith("weixin://wap/pay?") || url.startsWith("alipays://platformapi/startApp?")) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
            else {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "http://www.qianniukeji.vip");
                webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//每打开一个页面，默认都先加载缓存，除非点击刷新按钮
                view.loadUrl(url, extraHeaders);
            }
            return true;




 /*   其次是方案2：WEBVIEW调用内置浏览器。START

           try{
                if(!url.startsWith("http://") && !url.startsWith("https://")){

                    if(url.startsWith("weixin"))
                    {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                }
            }catch (Exception e){//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
            }
            return super.shouldOverrideUrlLoading(view, url);
    END*/

             //最后是方案3WEBVIEW自己不做任何处理
      /*    view.loadUrl(url);
            if (mWebsiteChangeListener != null) {
                mWebsiteChangeListener.onUrlChange(url);
            }
            return true;*/
        }

    }

    WebChromeClient webChromeClient = new WebChromeClient() {

        //=========HTML5定位==========================================================
        //需要先加入权限
        //<uses-permission android:name="android.permission.INTERNET"/>
        //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
        //=========HTML5定位==========================================================


        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.HitTestResult result = view.getHitTestResult();
            String data = result.getExtra();
            view.loadUrl(data);
            return true;
        }
        //=========多窗口的问题==========================================================

        //=========顶部进度条的进度更新===============================
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            if (newProgress == 100) {
                mProgressBar.setVisibility(View.GONE);
//                isNotTop = true;
            } else {
                if (mProgressBar.getVisibility() == View.GONE)
                    mProgressBar.setVisibility(View.VISIBLE);
//                if (isNotTop && mProgressBar.getVisibility() == VISIBLE) {
//                    if (mWebsiteChangeListener != null) {
//                        mWebsiteChangeListener.onWebsiteChangeBackTop();
//                        isNotTop = false;
//                    }
//                }
                mProgressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mWebsiteChangeListener != null) {
                mWebsiteChangeListener.onWebsiteChange(title);
            }
        }
    };


    public void setWebsiteChangeListener(WebsiteChangeListener websiteChangeListener) {
        this.mWebsiteChangeListener = websiteChangeListener;

    }
    public interface WebsiteChangeListener {
        void onWebsiteChange(String title);

        void onUrlChange(String url);
//        void onWebsiteChangeBackTop();
    }
}
